package com.zx.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatiesUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static final ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
    static {
//        加载配置信息，构建session工厂
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession() {
        SqlSession session = tl.get();
        if (session == null) {
            session = sqlSessionFactory.openSession();
            tl.set(session);
        }
        return session;
    }

    public static void closeSession() {
        SqlSession session = openSession();
        session.close();
    }

    public static void commit() {
        SqlSession session = openSession();
        session.commit();
        closeSession();
    }

    public static void rollback() {
        SqlSession session = openSession();
        session.rollback();
        closeSession();
    }

    public static <T> T getMapper(Class<T> clazz) {
        SqlSession session = openSession();
        T mapper = session.getMapper(clazz);
        return mapper;
    }


}
